//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 王佳琳 on 16/2/18.
//  Copyright © 2016年 王佳琳. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class OAuthViewController: UIViewController {
    
    //定义一个属性的webView
    let webView = UIWebView()
    //MARK: 关闭视图控制器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func testAccount() {
        //本地代码和webView交互
        let jsString = "document.getElementById('userId').value = '18086791881' , document.getElementById('passwd').value = '823414483wjl'"
        //通过一个字符串对象来执行 JavaScript代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        //设置webView代理
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //手写代码  根视图的背景颜色默认是  透明的
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "testAccount")
        
        //使用webView加载授权页面
        loadOauthPage()
        
    }
    //在页面将要消失的时候 dismiss
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //加载授权页面
    private func loadOauthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        //获取URL对象
        let url = NSURL(string: urlString)!
        //获取request对象
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)

    }
    
   

}

//注意 : 在设置代理的时候  如果不实现规定的代理方法 编译器会报错
//扩展  专门处理webView 的代理协议方法

extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        //开启指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    //获取收取成功后的code(授权码)
    //协议方法  返回值 为  BOOl类型  一般返回 true 提供协议的对象才能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            //URLString 为空
            return false
        }
        
        //判断urlString中是否包含 code码
        if urlString.containsString("code") {
            //截取对应的code字符串
            //query 获取URL的参数的字段个对应值
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(urlString,query,code)
            //用code码换取  token(令牌)
            //loadAccessToken(code)
            
            AccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                //执行dismiss
//                self.dismissViewControllerAnimated(true, completion: nil)
                if isSuccess {
                    //登陆成功
                    self.dismissViewControllerAnimated(true, completion: nil)
                    
                    //登陆成功之后  将跟视图控制器设置为  欢迎页面
                    NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: nil)

                    print("come here oauth")
                } else {
                    //登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败,请检查网络")
                }
            })

            
            return false
            
        }
        return true
    }
    
}
